import { Form, Input, Checkbox, Radio } from 'antd';
import React, { useEffect } from 'react';
import { connect } from 'umi';
import findLastIndex from 'lodash/findLastIndex';
import { cloneDeep } from 'lodash';
import styles from '../index.less';
import SelectOption from './SelectOption';

const { TextArea } = Input;

const RightPanel = ({
    dispatch,
    activeData,
    form,
    listCenter,
    setListCenter,
    editing,
    setEditing,
    cRef,
    errArr,
    setErrArr
}) => {
    const { getFieldDecorator, getFieldsValue, resetFields } = form;

    React.useImperativeHandle(cRef, () => ({
        resetFields
    }));
    // 监听输入变化
    const values = getFieldsValue();
    // 监听变化，更新值
    useEffect(() => {
        const obj = cloneDeep(activeData);
        if (!editing) return;
        if (activeData.cmpType !== 'common') {
            console.log(values.applyType);
            if (activeData.applyType !== undefined) {
                obj.applyType = values.applyType;
            }
        }

        // 常用组件
        // 把输入的值更新
        if (activeData) {
            // 单选框，复选框的时候不需要placeholder
            if (activeData.options && activeData.options.placeholder !== undefined) {
                if (values.placeholder) {
                    obj.options.placeholder = values.placeholder;
                } else {
                    obj.options.placeholder = '请输入';
                }
            }
            if (activeData.rules !== undefined) {
                if (obj.rules[0]) {
                    obj.rules[0].required = values.required;
                    // 如果当前有是否作为必填项的属性，就给他赋值
                    if (activeData.proCondition !== undefined) {
                        obj.proCondition = values.required;
                        if (values.required) {
                            dispatch({
                                type: 'workFlowModel/addPCondition',
                                payload: obj
                            });
                        } else {
                            dispatch({
                                type: 'workFlowModel/delPCondition',
                                payload: obj
                            });
                        }
                    }
                }
            }
            // label
            if (activeData.label !== undefined) {
                obj.label = values.label;
            }
            // 标题值
            if (activeData.titleValue !== undefined) {
                obj.titleValue = values.titleValue;
            }
            // 通过type类型来做不同的赋值逻辑
            if (activeData.dataList !== undefined) {
                obj.dataList = values.dataList;
            }
            // 时间范围
            if (activeData.pickerType !== undefined) {
                obj.pickerType = values.pickerType;
            }
            // 日期类型
            if (activeData.dataType !== undefined) {
                obj.dataType = values.dataType;
            }
            // 摘要
            if (activeData.isSummary !== undefined) {
                obj.isSummary = values.isSummary;
            }
            // 链接文本
            if (activeData.linkText !== undefined) {
                obj.linkText = values.linkText;
            }
            // 链接url
            if (activeData.linkUrl !== undefined) {
                obj.linkUrl = values.linkUrl;
            }
            // 表单item的额外的提示信息
            if (activeData.extra !== undefined) {
                obj.extra = values.extra;
            }
            // 下拉是否多选
            if (activeData?.options && activeData?.options?.multiple !== undefined) {
                obj.options = { ...obj?.options, multiple: values.optionsMultiple };
            }

            if (activeData?.uploadProps?.describe !== undefined) {
                obj.uploadProps.describe = values.describe;
            }

            const existIndex = listCenter.findIndex(listItem => listItem.formId === obj.formId);
            if (existIndex > -1) {
                const newList = [...listCenter.slice(0, existIndex), obj, ...listCenter.slice(existIndex + 1)];
                setListCenter(newList);
            }
        }

        // 组件中是否有错误信息，有的话不可以发布
        form.validateFields((err, vals) => {
            if (err) {
                setErrArr([...errArr, { formId: activeData.formId, label: vals.label }]); // / 当前只有一个下拉重复值的验证，如果有多个项需要验证应该要处理form的错误数组
            } else {
                const delErrArrID = errArr.findIndex(item => item.formId === activeData.formId);
                if (delErrArrID > -1) {
                    setErrArr(errArr.slice(delErrArrID, 0));
                }
            }
        });
    }, [JSON.stringify(values)]);

    // 渲染
    const getComponents = item => {
        const temp = [];

        // 定制组件
        if (item && item.cmpType !== 'common') {
            if (item.tag === 'TurnoverByLeader') {
                temp.push(
                    <Form.Item key={`${item.key}${temp.length}`}>
                        {getFieldDecorator('applyType', {
                            valuePropName: 'checked',
                            initialValue: item.applyType
                        })(<Checkbox>主管代申请</Checkbox>)}
                    </Form.Item>
                );
            }
        }

        // 常用组件
        if (item && item.cmpType === 'common') {
            if (item && item.label !== undefined && item.tag !== 'Title' && item.tag !== 'Link') {
                temp.push(
                    <Form.Item
                        colon={false}
                        label={
                            <span className={styles.formItemLabel}>
                                <b>标题：</b>
                                <span>最多50个字</span>
                            </span>
                        }
                        {...item.layout}
                        key={`${item.key}${temp.length}`}
                    >
                        {getFieldDecorator('label', {
                            rules: item.rules,
                            initialValue: item ? item.label : '请输入'
                        })(<Input placeholder="请输入" maxLength={50} />)}
                    </Form.Item>
                );
            }
            if (item && item.options.placeholder !== undefined) {
                temp.push(
                    <Form.Item
                        colon={false}
                        label={
                            <span className={styles.formItemLabel}>
                                <b>提示文字：</b>
                                <span>最多20个字</span>
                            </span>
                        }
                        {...item.layout}
                        key={`${item.key}${temp.length}`}
                    >
                        {getFieldDecorator('placeholder', {
                            initialValue: item && item.options ? item.options.placeholder : '请输入'
                        })(<Input placeholder="请输入" maxLength={20} />)}
                    </Form.Item>
                );
            }
            if (item && item.rules && item.rules[0] && item.rules[0].required !== undefined) {
                temp.push(
                    <Form.Item
                        colon={false}
                        label={
                            <span className={styles.formItemLabel}>
                                <b>验证：</b>
                            </span>
                        }
                        {...item.layout}
                        key={`${item.key}${temp.length}`}
                    >
                        {getFieldDecorator('required', {
                            valuePropName: 'checked',
                            initialValue: item && item.rules ? item.rules[0].required : false
                        })(
                            item.proCondition !== undefined ? (
                                <Checkbox disabled={item?.isUsed || false}>必填 (勾选后可作为流程条件)</Checkbox>
                            ) : (
                                <Checkbox>必填</Checkbox>
                            )
                        )}
                    </Form.Item>
                );
            }
            if (item && item.tag === 'Date') {
                temp.push(
                    <Form.Item
                        colon={false}
                        label={
                            <span className={styles.formItemLabel}>
                                <b>日期类型：</b>
                            </span>
                        }
                        {...item.layout}
                        key={`${item.key}${temp.length}`}
                    >
                        {getFieldDecorator('dataType', {
                            initialValue: item && item.dataType ? item.dataType : 'year'
                        })(
                            <Radio.Group>
                                <Radio value="year">年月日</Radio>
                                <Radio value="yearTime">年月日 时分秒</Radio>
                                <Radio value="hourMinute">年月日 时分</Radio>
                                <Radio value="month">月份</Radio>
                            </Radio.Group>
                        )}
                    </Form.Item>
                );
            }
            if (item && item.dataList !== undefined) {
                temp.push(
                    <Form.Item
                        colon={false}
                        label={
                            <span className={styles.formItemLabel}>
                                <b>选项：</b>
                            </span>
                        }
                        {...item.layout}
                        key={`${item.key}${temp.length}`}
                    >
                        {getFieldDecorator('dataList', {
                            initialValue: item && item.dataList ? item.dataList : [],
                            rules: [
                                {
                                    validator(_, value, callback) {
                                        if (value) {
                                            const isRepeat = value.some(v => {
                                                if (
                                                    findLastIndex(value, { value: v.label }) !==
                                                    value.findIndex(it => it.label === v.label)
                                                ) {
                                                    return true;
                                                }
                                                return false;
                                            });
                                            if (isRepeat) {
                                                callback('选项名称重复');
                                            } else {
                                                callback();
                                            }
                                        } else {
                                            callback();
                                        }
                                    }
                                }
                            ]
                        })(<SelectOption prefix={item.formId} />)}
                    </Form.Item>
                );
            }
            if (item && item.pickerType !== undefined) {
                temp.push(
                    <Form.Item
                        colon={false}
                        label={
                            <span className={styles.formItemLabel}>
                                <b>选项：</b>
                            </span>
                        }
                        {...item.layout}
                        key={`${item.key}${temp.length}`}
                    >
                        {getFieldDecorator('pickerType', {
                            initialValue: item && item.pickerType ? item.pickerType : 'yearPricker'
                        })(
                            <Radio.Group>
                                <Radio value="yearPricker">年月日</Radio>
                                <Radio value="hourPricker">年月日 时分秒</Radio>
                                <Radio value="hourMinutePricker">年月日 时分</Radio>
                            </Radio.Group>
                        )}
                    </Form.Item>
                );
            }
            if (item && item.titleValue !== undefined) {
                temp.push(
                    <Form.Item
                        colon={false}
                        label={
                            <span className={styles.formItemLabel}>
                                <b>标题：</b>
                                <span>最多50个字</span>
                            </span>
                        }
                        {...item.layout}
                        key={`${item.key}${temp.length}`}
                    >
                        {getFieldDecorator('titleValue', {
                            initialValue: item && item.titleValue ? item.titleValue : '标题'
                        })(<Input maxLength={50} />)}
                    </Form.Item>
                );
            }
            if (item && item.linkText !== undefined) {
                temp.push(
                    <Form.Item
                        colon={false}
                        label={
                            <span className={styles.formItemLabel}>
                                <b>链接文本：</b>
                                <span>最多500个字</span>
                            </span>
                        }
                        {...item.layout}
                        key={`${item.key}${temp.length}`}
                    >
                        {getFieldDecorator('linkText', {
                            initialValue: item && item.linkText ? item.linkText : '链接文本'
                        })(<TextArea rows={4} maxLength={500} />)}
                    </Form.Item>
                );
            }
            if (item && item.linkUrl !== undefined) {
                temp.push(
                    <Form.Item
                        colon={false}
                        label={
                            <span className={styles.formItemLabel}>
                                <b>链接跳转地址：</b>
                                <span>最多500个字</span>
                            </span>
                        }
                        {...item.layout}
                        key={`${item.key}${temp.length}`}
                    >
                        {getFieldDecorator('linkUrl', {
                            initialValue: item && item.linkUrl ? item.linkUrl : ''
                        })(<TextArea placeholder="请输入链接跳转地址" maxLength={500} />)}
                    </Form.Item>
                );
            }
            if (item && item.isSummary !== undefined) {
                temp.push(
                    <Form.Item
                        colon={false}
                        label={
                            <span className={styles.formItemLabel}>
                                <b>摘要：</b>
                            </span>
                        }
                        {...item.layout}
                        key={`${item.key}${temp.length}`}
                    >
                        {getFieldDecorator('isSummary', {
                            valuePropName: 'checked',
                            initialValue: item && item.isSummary ? item.isSummary : false
                        })(<Checkbox>显示摘要 (如不勾选，打印时不显示该项)</Checkbox>)}
                    </Form.Item>
                );
            }
            if (item && item.extra !== undefined) {
                temp.push(
                    <Form.Item
                        colon={false}
                        label={
                            <span className={styles.formItemLabel}>
                                <b>额外的提示信息：</b>
                                <span>最多100个字</span>
                            </span>
                        }
                        {...item.layout}
                        key={`${item.key}${temp.length}`}
                    >
                        {getFieldDecorator('extra', {
                            initialValue: item.extra
                        })(<TextArea maxLength={100} />)}
                    </Form.Item>
                );
            }
            if (item && item?.options?.multiple !== undefined) {
                temp.push(
                    <Form.Item
                        colon={false}
                        label={
                            <span className={styles.formItemLabel}>
                                <b>多选:</b>
                            </span>
                        }
                        {...item.layout}
                        key={`${item.key}${temp.length}`}
                    >
                        {getFieldDecorator('optionsMultiple', {
                            valuePropName: 'checked',
                            initialValue: item?.options?.multiple
                        })(<Checkbox>选择后可以多选</Checkbox>)}
                    </Form.Item>
                );
            }
            if (item && item.tag === 'OssUpload') {
                temp.push(
                    <Form.Item
                        colon={false}
                        label={
                            <span className={styles.formItemLabel}>
                                <b>描述：</b>
                            </span>
                        }
                        {...item.layout}
                        key={`${item.key}${temp.length}`}
                    >
                        {getFieldDecorator('describe', {
                            initialValue: item ? item.uploadProps.describe : ''
                        })(
                            <Input.TextArea
                                maxLength={500}
                                placeholder="请输入描述信息"
                                autoSize={{ minRows: 3 }}
                            ></Input.TextArea>
                        )}
                    </Form.Item>
                );
            }
        }

        // eslint-disable-next-line consistent-return
        return temp;
    };
    return (
        <div className="right-board" onClick={() => setEditing(true)}>
            <Form className={styles.rightBoardForm}>{getComponents(activeData)}</Form>
        </div>
    );
};

export default connect(({ workFlowModel }) => ({
    workFlowModel
}))(Form.create()(RightPanel));
